$(function () {
  let search = location.search;
  //   解析
  // 全局id
  let id = new URLSearchParams(search).get("value");

  // 1.渲染图片即可显示
  $("#inputCover").on("change", function () {
    let file = this.files[0];
    let src = URL.createObjectURL(file);
    $("#coverimg").prop("src", src);
  });

  // 2.渲染所有分类
  function renderCategory() {
    $.ajax({
      url: "http://localhost:8080/api/v1/admin/category/list",
      headers: { Authorization: localStorage.getItem("token") },
      dataType: "json",
      success: function (res) {
        let list = res.data;
        if (res.code === 200) {
          let html = "";
          html += `<option value=''>所有分类</option>`;
          list.forEach(function (data) {
            html += `<option value='${data.id}'>${data.name}</option>`;
          });
          $("#category").html(html);
          renderArticle();
        } else {
          console.log("失败");
          console.log(res);
        }
      },
    });
  }
  // 3.渲染所有分类
  renderCategory();

  // 4.渲染日期
  function renderDate() {
    layui.use("laydate", function () {
      var laydate = layui.laydate;
      //执行一个laydate实例
      laydate.render({
        elem: "#articleDate", //指定元素
      });
    });
  }
  // 4.渲染日期
  renderDate();

  // 5.富文本
  function renderRichText() {
    tinymce.init({
      selector: "#articleContent",
      language: "zh_CN", //注意大小写
    });
  }
  // 5.富文本
  renderRichText();

  // 6.发布文章公共函数
  function publicArticle(send) {
    let content = tinyMCE.editors["articleContent"].getContent();
    let formdata = new FormData($("#form")[0]);
    formdata.append("content", content);
    formdata.append("state", send);
    $.ajax({
      url: "http://localhost:8080/api/v1/admin/article/publish",
      type: "post",
      data: formdata,
      processData: false,
      contentType: false,
      headers: { Authorization: localStorage.getItem("token") },
      success: function (res) {
        if (res.code === 200) {
          location.href = "article_list.html";
        } else {
          console.log("失败");
          console.log(res);
        }
      },
    });
  }
  // 6.发布文章公共函数
  publicArticle();

  // 7.点击发布文章
  $("#form .btn-edit").on("click", function () {
    publicArticle("已发布");
  });

  // 8.保存草稿
  $(".btn-draft").on("click", function () {
    publicArticle("");
  });

  // 9.填充文字
  function renderText() {
    $.ajax({
      url: "http://localhost:8080/api/v1/admin/article/search",
      headers: { Authorization: localStorage.getItem("token") },
      data: { id },
      success: function (tex) {
        if (tex.code === 200) {
          // 填充数据
          $("#inputTitle").val(tex.data.title);
          $("#coverimg").prop("src", tex.data.cover);
          $("#category").val(tex.data.categoryId);
          $("#articleDate").val(tex.data.date);
          $("#articleContent").val(tex.data.content);
        } else {
          console.log("失败");
          console.log(res);
        }
      },
    });
  }
  renderText();
});
